package com.can.forkJoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

/**
 * 同一个任务，别人效率比你高几十倍
 */
public class Test {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        test1(); //num=500000000500000000时间：6667
        test2(); //num=500000000500000000时间：4259
        test3(); //num=500000000500000000时间：297
    }

    //普通程序员
    public static void test1(){
        Long sum = 0L;
        long start = System.currentTimeMillis();
        for (Long i = 1L; i <= 10_0000_0000; i++) { //10_0000_0000; 十亿
            sum += i;
        }
        long end = System.currentTimeMillis();
        System.out.println("num="+sum+"时间："+(end-start));
    }

    //会使用ForkJoin
    public static void test2() throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Long> task = new ForkJoinDemo01(0L, 10_0000_0000L);
        ForkJoinTask<Long> submit = forkJoinPool.submit(task);
        Long sum = submit.get();
//        forkJoinPool.execute();//同步
//        forkJoinPool.submit();//异步
        long end = System.currentTimeMillis();
        System.out.println("num="+sum+"时间："+(end-start));
    }

    //Stream并行流
    public static void test3(){
        long start = System.currentTimeMillis();
        //Stream并行流 () (]
        //rangeClosed包含最后的结束节点，range不包含。
        long sum = LongStream.rangeClosed(0L, 10_0000_0000L).parallel().reduce(0,Long::sum);
        long end = System.currentTimeMillis();
        System.out.println("num="+sum+"时间："+(end-start));
    }
}